const { task } = require("hardhat/config");
const { networkConfig } = require("../helper-hardhat-config");

task("burn-and-cross")
    .addOptionalParam("chainselector", "chain selector of dest chain")
    .addOptionalParam("receiver", "receiver address on dest chain")
    .addParam("tokenid", "token id to ben cross chain")
    .setAction(async(args, hre) => {
        let chainSelector
        let receiver
        const tokenId = args.tokenid
        const { firstAccount } = await getNamedAccounts()

        if(args.chainselector) {
            chainSelector = args.chainselector
        } else {
            chainSelector = networkConfig[network.config.chainId].companionChainSelector
            console.log("chainSelector is not set on command")
        }
        console.log(`chainSelector is ${chainSelector}`)

        if(args.receiver) {
            receiver = args.receiver
        } else {
            const nftPoolLockAndReleaseDeployment = 
                await hre.companionNetworks["destChain"].deployments.get("NFTPoolLockAndRelease")
            receiver = nftPoolLockAndReleaseDeployment.address
            console.log("receiver is not set on command")
        }
        console.log(`receiver is ${receiver}`)

        //transfer link token to address of pool
        const linkTokenAddress = networkConfig[network.config.chainId].linkToken
        const linkToken = await ethers.getContractAt("LinkToken", linkTokenAddress)
        const nftPoolBurnAndMint = await ethers.getContract("NFTPoolBurnAndMint", firstAccount)
        const transferTx = await linkToken.transfer(nftPoolBurnAndMint.target, ethers.parseEther("0.5"))
        await transferTx.wait(6)
        const balance = await linkToken.balanceOf(nftPoolBurnAndMint.target)
        console.log(`balance of pool is ${balance}`)

        //approve pool address to call transferFrom
        const wnft = await ethers.getContract("WrappedMyToken", firstAccount)
        await wnft.approve(nftPoolBurnAndMint.target, tokenId)
        console.log("approve successfully")

        //call burnAndSendNFT
        const burnAndSendNFTTx = await nftPoolBurnAndMint.burnAndSendNFT(tokenId, firstAccount, chainSelector, receiver)
        console.log(`ccip transaction is sent, the tx hash is ${burnAndSendNFTTx.hash}`)
    })

module.exports = {}